package my.jessyan.mvpart.mvp.refresh;


import ohos.agp.components.*;
import ohos.app.Context;
import ohos.multimodalinput.event.TouchEvent;

/**
 * author : liupeng
 * date   : 2021/3/25
 * desc   : 刷新框架
 */
public class PullToRefreshLayout extends DirectionalLayout implements Component.TouchEventListener, Component.LayoutRefreshedListener {
    /**
     * 按下的坐标
     */
    private int downY;
    /**
     * 当前状态
     */
    private BaseRefreshLayout.REFRESH mCurrentState = BaseRefreshLayout.REFRESH.TAP_TO_REFRESH;

    /**
     * 头部的高度
     */
    private int headerViewHeight;
    /**
     * 尾部的高度
     */
    private int footViewHeight;

    /**
     * 是否按下
     */
    private Boolean isDownAction = false;

    private TextOverComponent mMediaHeadView;
    private ListContainer mListContainer;

    public PullToRefreshLayout(Context context) {
        this(context, null);
    }

    public PullToRefreshLayout(Context context, AttrSet attrSet) {
        this(context, attrSet, "");
    }

    public PullToRefreshLayout(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);

        setLayoutRefreshedListener(this);
        setTouchEventListener(this);

    }

    private Boolean isFrist = true;

    @Override
    public void onRefreshed(Component component) {
        Component head = getComponentAt(0);
        Component child = getComponentAt(1);
        if (isFrist) {
            isFrist = false;
            mMediaHeadView = (TextOverComponent) head;
            mListContainer = (ListContainer) child;

            headerViewHeight = mMediaHeadView.getHeight();
            mMediaHeadView.setMarginTop(-headerViewHeight);
        }
    }

    /**
     * 设置下拉刷新的头部组件
     *
     * @param headOverComponent 下拉刷新的头部组件
     */
    public void setRefreshOverComponent(TextOverComponent headOverComponent) {
        if (mMediaHeadView != null) {
            removeComponent(mMediaHeadView);
        }
        mMediaHeadView = headOverComponent;
        LayoutConfig config = new LayoutConfig(LayoutConfig.MATCH_PARENT, LayoutConfig.MATCH_CONTENT);
        addComponent(mMediaHeadView, 0, config);
    }

    /**
     * 是否移动到顶部
     *
     * @return true 移动到顶部
     */
    private Boolean isMoveTop() {
        if (mListContainer.getComponentAt(0) == null) {
            return false;
        }
        if (mListContainer.getComponentAt(0).getTop() < 0) {
            if (mListContainer.getFirstVisibleItemPosition() == 0) {
                if (mMediaHeadView.getMarginTop() > -headerViewHeight) {
                    return true;
                }
                return false;
            }
            return false;
        } else if (mListContainer.getFirstVisibleItemPosition() == 0) {
            if (mListContainer.getComponentAt(0).getTop() == 0) {
                return true;
            }
            return false;
        }
        return false;
    }

    @Override
    public boolean onTouchEvent(Component component, TouchEvent event) {
        switch (event.getAction()) {
            case TouchEvent.PRIMARY_POINT_DOWN:
                if (mCurrentState == BaseRefreshLayout.REFRESH.TAP_TO_REFRESH) {
                    downY = getRawY(event);
                }
                isDownAction = true;
                break;
            case TouchEvent.CANCEL:
            case TouchEvent.PRIMARY_POINT_UP:
                //释放刷新  刷新逻辑
                if (mCurrentState == BaseRefreshLayout.REFRESH.RELEASE_TO_REFRESH) {
                    mMediaHeadView.setMarginTop(0);
                    mListContainer.scrollTo(0, 0);
                    mCurrentState = BaseRefreshLayout.REFRESH.REFRESHING;
                    listener.onRefresh();
                } else {
                    int moveDistance = getRawY(event) - downY;
                    mCurrentState = BaseRefreshLayout.REFRESH.TAP_TO_REFRESH;
                    if (moveDistance > 0) {
                        mMediaHeadView.setMarginTop(-headerViewHeight);
//                        mMediaFoodView.setMarginBottom(-mMediaFoodView.topMargin);
                        mMediaHeadView.setFinishRefresh();
                    }
                }
                isDownAction = false;
                break;
            case TouchEvent.POINT_MOVE:

                int moveDistance = getRawY(event) - downY;
                if (isMoveTop() && mCurrentState != BaseRefreshLayout.REFRESH.REFRESHING && isDownAction) {
                    int marginTop = -headerViewHeight + moveDistance;
                    if (moveDistance <= 0) {
                        marginTop = -headerViewHeight;
                    }
                    mMediaHeadView.setMarginTop(marginTop);

                    if (moveDistance > 0) {
                        mListContainer.scrollTo(0, 0);
                    }
                    //滑动距离大于顶部高度
                    if (moveDistance > headerViewHeight) {
                        //释放刷新
                        mCurrentState = BaseRefreshLayout.REFRESH.RELEASE_TO_REFRESH;
                    } else {
                        //下拉刷新
                        mCurrentState = BaseRefreshLayout.REFRESH.PULL_TO_REFRESH;
                    }
                    mMediaHeadView.setRefreshState(mCurrentState);
                } else {
                    downY = getRawY(event);
                }
                break;
        }

        return true;
    }

    /**
     * 刷新成功
     */
    public void refreshFinish() {
        mListContainer.scrollTo(0, 0);
        mMediaHeadView.setMarginTop(-headerViewHeight);
        mCurrentState = BaseRefreshLayout.REFRESH.TAP_TO_REFRESH;
        mMediaHeadView.setRefreshState(mCurrentState);
    }

    /**
     * 加载成功
     */
    public void loadSuccess() {
//        mMediaFoodView.setMarginBottom(-mMediaFoodView.topMargin);
//        mCurrentState = REFRESH.TAP_TO_REFRESH;
//        mMediaFoodView.setRefreshState(mCurrentState);
    }


    private RefreshListener listener;

    public void setRefreshListener(RefreshListener listener) {
        this.listener = listener;
    }

    private int getRawY(TouchEvent ev) {
//        float sumX = 0 ;
        double sumY = 0.0f;
        int count = ev.getPointerCount();

        for (int i = 0; i < count; i++) {
//            sumX += ev.getPointerScreenPosition(i).getX();
            sumY += ev.getPointerScreenPosition(i).getY();
        }

        return (int) (sumY / count);
    }

    /**
     * 查找ListContainer
     * 目前只针对ListContainer处理  Scrollview以后再增加
     *
     * @return ListContainer
     */
    public static ListContainer findListContainer(ComponentContainer componentContainer) {
        Component child = componentContainer.getComponentAt(1);
        if (child instanceof ListContainer) {
            return (ListContainer) child;
        }
        if (child instanceof ComponentContainer) {//往下多找一层
            Component tempChild = ((ComponentContainer) child).getComponentAt(0);
            if (tempChild instanceof ListContainer) {
                child = tempChild;
            }
        }
        return (ListContainer) child;
    }

    public interface RefreshListener {
        void onRefresh();

        void onLoadMore();
    }
}
